﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Controls;
using System.Xml.Linq;
using System.Windows;
using System.Windows.Media;

namespace Twi.COMMON.WPF
{
    public static class ItemsControlExtensions
    {
        /// <summary>
        /// 添加子项，并且排序
        /// </summary>
        /// <param name="me"></param>
        /// <param name="insertion"></param>
        public static void AddChild(this ItemsControl me, FrameworkElement insertion)
        {
            for (int i = me.Items.Count - 1; i >= 0; i--)
            {
                XElement xeSortOrder = ((me.Items[i] as FrameworkElement).DataContext as XElement).Element("SortOrder");
                int sortOrder = xeSortOrder.Value.Trim() == "" ? 0 : int.Parse(xeSortOrder.Value.Trim());

                XElement xeSortOrderInsertion = ((insertion as FrameworkElement).DataContext as XElement).Element("SortOrder");
                int sordOrderInsertion = xeSortOrderInsertion.Value.Trim() == "" ? 0 : int.Parse(xeSortOrderInsertion.Value);
                if (sordOrderInsertion >= sortOrder)
                {
                    if (i == me.Items.Count)//如果插入物的排序索引最大, 则应该放在队列的最后
                    {
                        me.Items.Add(insertion);
                    }
                    else
                    {
                        me.Items.Insert(i + 1, insertion);//插入位置在当前位置的后面
                    }
                    return;
                }
            }
            me.Items.Insert(0, insertion); //插入物的排序索引是最小的
        }

        /// <summary>
        /// 更新后自动刷新排序
        /// </summary>
        /// <param name="me"></param>
        public static void RefreshParentAfterUpdated(this FrameworkElement me)
        {
            ItemsControl parent = me.Parent as ItemsControl;
            parent.Items.Remove(me);
            parent.AddChild(me);
        }            

        public static void Remove(this FrameworkElement me)
        {
            (me.Parent as ItemsControl).Items.Remove(me);
        }
    }
}
